﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DiBang.Common;
using DiBang.Sql;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Size = System.Drawing.Size;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using System.Windows;
using System.IO;
using System.Drawing.Imaging;
using System.Configuration;
using System.Data.SqlClient;


namespace ChangWuDiBang
{
    public partial class FrmDiBangInput : Office2007Form
    {
        private FilterInfoCollection videoDevices;
        //private VideoCaptureDevice videoSource;
        delegate void UpdateTextEventHandler(string text);  //委托，此为重点
        UpdateTextEventHandler updateText;

        public UserInfo _UserInfo
        {
            get;
            set;
        }

        private enum InputMode
        {
            MaoZhong,PiZhong,None
        }

        private Enum WeightMode=InputMode.None;

        SqlLib sqlLib = new SqlLib();
        SqlExtend sqlExtend = new SqlExtend();

        public FrmDiBangInput()
        {
            this.EnableGlass = false;
            InitializeComponent();
        }

        private void FrmDiBangInput_Load(object sender, EventArgs e)
        {
            try
            {
                splitContainer1.Panel1Collapsed = false;
                splitContainer1.Panel2Collapsed = true;

                this.txtUserID.Text = _UserInfo.UserID;
                //一直刷新时间
                lblVDate.Text = sqlExtend.GetSysTime();
                this.timer1.Enabled = true;
                this.timer1.Start();

                //初始化COM口
                SerialPortInit();

                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                foreach (FilterInfo device in videoDevices)
                {
                    cmbFirstCamera.Items.Add(device.Name);
                }
                cmbFirstCamera.SelectedIndex = -1;
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        //接收SerialPort数据
        private void SerialPortInit()
        {
            string portName = ConfigurationManager.AppSettings["PortName"].ToString();
            string baudRate = ConfigurationManager.AppSettings["BaudRate"].ToString();
            int iBaudRate = int.Parse(baudRate);
            serialport = new System.IO.Ports.SerialPort(portName, iBaudRate);
            try
            {
                serialport.Close();
                serialport.Dispose();

                serialport.Open();
                lblVSerialPortState.Text = "端口OK!";
                lblVSerialPortState.BackColor = Color.LightGreen;
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                lblVSerialPortState.Text = "端口异常!";
                lblVSerialPortState.BackColor = Color.Red;
            }
        }

        private void serialport_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //byte[] readBuffer = new byte[serialport.ReadBufferSize];
            //spReceive.Read(readBuffer, 0, readBuffer.Length);
            //this.Invoke(updateText, new string[] { Encoding.Unicode.GetString(readBuffer) });

            string readString = serialport.ReadExisting();
            this.Invoke(updateText, new string[] { readString });
        }

        private void UpdateTextBox(string text)
        {
            txtWeight.Text = text;
        }

        private enum CameraMode
        { 
            CONNECT,DISCONNECT
        }

        private bool FirstCamera(CameraMode mode)
        {
            bool retBool = true;
            if (mode.Equals(CameraMode.CONNECT))
            {
                VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[cmbFirstCamera.SelectedIndex].MonikerString);
                videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
                videoSource.DesiredFrameRate = 1;

                vspFirst.VideoSource = videoSource;
                vspFirst.Start();
            }
            else if (mode.Equals(CameraMode.DISCONNECT))
            {
                vspFirst.SignalToStop();
                vspFirst.WaitForStop();
            }
            else
            {
                MessageBoxEx.Show("输入模式不正确!", "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                retBool = false;    
            }

            return retBool;
        }

        private void btnFirstPhoto_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnFirstPhoto.Text == "拍照")
                {
                    if (vspFirst.IsRunning)
                    {
                        BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                        vspFirst.GetCurrentVideoFrame().GetHbitmap(),
                                        IntPtr.Zero,
                                         Int32Rect.Empty,
                                        BitmapSizeOptions.FromEmptyOptions());
                        PngBitmapEncoder pE = new PngBitmapEncoder();
                        pE.Frames.Add(BitmapFrame.Create(bitmapSource));

                        MemoryStream ms = new MemoryStream();
                        pE.Save(ms);

                        //Stream转换成图片
                        Image image = Image.FromStream(ms, true);
                        picFirst.Image = image;

                        //Byte[] imgbyte = new Byte[ms.Length];
                        //ms.Read(imgbyte, 0, imgbyte.Length);
                    }
                    
                    //转换视角
                    splitContainer1.Panel1Collapsed = true ;
                    splitContainer1.Panel2Collapsed = false;
                    btnFirstPhoto.Text = "返回";
                }
                else
                {
                    //转换视角
                    splitContainer1.Panel1Collapsed = false;
                    splitContainer1.Panel2Collapsed = true;
                    btnFirstPhoto.Text = "拍照";
                }
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        private void btnFirstConnet_Click(object sender, EventArgs e)
        {
            if (btnFirstConnet.Text == "断开")
            {
                if (FirstCamera(CameraMode.DISCONNECT))
                {
                    btnFirstConnet.Text = "连接";
                }
            }
            else
            {
                if (FirstCamera(CameraMode.CONNECT))
                {
                    btnFirstConnet.Text = "断开";
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!sqlExtend.UserPwdCheck(txtUserID.Text.Trim(), txtPwd.Text.Trim()))
                    throw new Exception("用户ID或密码不存在!");

                DialogResult diaR = MessageBoxEx.Show("是否要保存?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (diaR == DialogResult.No)
                    return;

                string timeKey = sqlExtend.GetTimeKey();
                string imageID = "IMAGE_" + timeKey;

                if (ckbNewAdd.Checked)
                {
                    CheckParam(InputMode.MaoZhong);//新建的时候检查参数
                    //存入记录的数据
                    Dictionary<string, object> dibangSet = new Dictionary<string, object>();
                    dibangSet.Clear();
                    dibangSet.Add("PIN_MING", txtPinMing.Text.Trim());
                    dibangSet.Add("CHE_HAO", txtCheHao.Text.Trim());
                    dibangSet.Add("OTHER", txtOther.Text.Trim());
                    dibangSet.Add("MaoZhong", Base64Encoding.BaseEncoding(txtMaoZhong.Text.Trim()));

                    dibangSet.Add("CREATE_USER_ID", txtUserID.Text.Trim());
                    dibangSet.Add("CREATE_TIME", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                    dibangSet.Add("LAST_EVENT_NAME", "称皮重");
                    dibangSet.Add("LAST_EVENT_USER_ID", txtUserID.Text.Trim());
                    dibangSet.Add("LAST_EVENT_TIMEKEY", timeKey);

                    if (sqlLib.InsertTable("DB_DIBANG", dibangSet) >= -1)
                    {
                        sqlExtend.MakeDiBangHistory(timeKey);//插入履历
                        MessageBoxEx.Show("输入存入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    CheckParam(InputMode.PiZhong);//皮重检查参数

                    MemoryStream msFirst = new MemoryStream();
                    picFirst.Image.Save(msFirst, ImageFormat.Bmp);
                    msFirst.Dispose();
                    byte[] byteFirstPic = msFirst.GetBuffer();

                    //存入图片
                    Dictionary<string, object> imageSet = new Dictionary<string, object>();
                    imageSet.Clear();
                    imageSet.Add("IMAGE_ID", imageID);
                    imageSet.Add("FIRST_PHOTO", byteFirstPic);
                    imageSet.Add("CREATE_USER_ID", txtUserID.Text.Trim());
                    imageSet.Add("CREATE_TIME", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                    imageSet.Add("LAST_EVENT_NAME", "IMAGE_CREATE");
                    imageSet.Add("LAST_EVENT_USER_ID", txtUserID.Text.Trim());
                    imageSet.Add("LAST_EVENT_TIMEKEY", timeKey);
                    sqlLib.InsertTable("DB_IMAGE", imageSet);

                    //存入记录的数据
                    Dictionary<string, object> dibangSet = new Dictionary<string, object>();
                    dibangSet.Clear();
                    dibangSet.Add("CHENG_DATE", lblVDate.Text.Trim());
                    dibangSet.Add("PIN_MING", txtPinMing.Text.Trim());
                    dibangSet.Add("CHE_HAO", txtCheHao.Text.Trim());
                    dibangSet.Add("OTHER", txtOther.Text.Trim());

                    dibangSet.Add("PiZhong", Base64Encoding.BaseEncoding(txtPiZhong.Text.Trim()));
                    dibangSet.Add("RongQiNum", txtRongQiNum.Text.Trim());
                    dibangSet.Add("RongQiZhong", Base64Encoding.BaseEncoding(txtRongQiZhong.Text.Trim()));
                    dibangSet.Add("JingZhong", Base64Encoding.BaseEncoding(txtJingZhong.Text.Trim()));
                    dibangSet.Add("IMAGE_ID", imageID);

                    dibangSet.Add("CompleteFlag", "Y");

                    dibangSet.Add("LAST_EVENT_NAME", "称毛重");
                    dibangSet.Add("LAST_EVENT_USER_ID", txtUserID.Text.Trim());
                    dibangSet.Add("LAST_EVENT_TIMEKEY", timeKey);

                    Dictionary<string, object> dibangWhere = new Dictionary<string, object>();
                    dibangWhere.Clear();
                    dibangWhere.Add("LAST_EVENT_TIMEKEY", lblVLastEventTimeKey.Text.Trim());

                    if (sqlLib.UpdateTable("DB_DIBANG", dibangSet,dibangWhere) >= -1)
                    {
                        sqlExtend.MakeDiBangHistory(timeKey);//插入履历
                        MessageBoxEx.Show("输入存入成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //Show出报表界面
                        DiBangPrintInfo dibangPrintInfo = new DiBangPrintInfo();

                        dibangPrintInfo.PinMing = txtPinMing.Text.Trim();
                        dibangPrintInfo.CheHao = txtCheHao.Text.Trim();
                        dibangPrintInfo.ChengZhongDate = lblVDate.Text.Trim();
                        dibangPrintInfo.MaoZhong = txtMaoZhong.Text.Trim();
                        dibangPrintInfo.PiZhong = txtPiZhong.Text.Trim();
                        dibangPrintInfo.RongQiNum = txtRongQiNum.Text.Trim();
                        dibangPrintInfo.RongQiZhong = txtRongQiZhong.Text.Trim();
                        dibangPrintInfo.JingZhong = txtJingZhong.Text.Trim();

                        dibangPrintInfo.FirstPic = Convert.ToBase64String(byteFirstPic);//报表图片显示

                        FrmDiBangPrint frmDiBangPrint = new FrmDiBangPrint();
                        frmDiBangPrint._DiBangPrintInfo = dibangPrintInfo;
                        frmDiBangPrint.ShowDialog();
                    }
                }
            }
            catch (Exception err)
            {
                MessageBoxEx.Show(err.Message, "Warming", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                txtPwd.Clear();
                txtComment.Clear();

                txtPinMing.Clear();
                txtCheHao.Clear();
                txtOther.Clear();

                txtMaoZhong.Clear();
                txtPiZhong.Clear();
                txtRongQiNum.Clear();
                txtRongQiZhong.Clear();
                txtJingZhong.Clear();

                WeightMode = InputMode.None;
                //
                picFirst.Image = null;
                btnFirstPhoto.Text = "拍照";
            }
        }

        private void CheckParam(InputMode mode)
        {
            //都要检查
            if(string.IsNullOrEmpty(txtPinMing.Text.Trim()))
            {
                txtPinMing.Focus();
                throw new Exception("品名不能为空!");
            }
            if (string.IsNullOrEmpty(txtCheHao.Text.Trim()))
            {
                txtCheHao.Focus();
                throw new Exception("车号不能为空!");
            }

            
            if (mode.Equals(InputMode.MaoZhong))
            {   
                //毛重新增信息状态下
                if (string.IsNullOrEmpty(txtMaoZhong.Text.Trim()))
                {
                    throw new Exception("毛重不能为空!");
                }
            }
            else if (mode.Equals(InputMode.PiZhong))
            {
                //皮重修改信息状态下
                if (string.IsNullOrEmpty(txtPiZhong.Text.Trim()))
                {
                    throw new Exception("皮重不能为空!");
                }
                if(string.IsNullOrEmpty(txtJingZhong.Text.Trim()))
                {
                    throw new Exception("净重不能为空!");
                }
                if(picFirst.Image==null)
                {
                    throw new Exception("视频截图不能为空!");
                }
                if (string.IsNullOrEmpty(lblVLastEventTimeKey.Text.Trim()))
                {
                    throw new Exception("毛重信息丢失!");
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //lblVDate.Text = sqlExtend.GetSysTime();
            InfoSet();
        }

        private void InfoSet()
        {
            lblVDate.Text = sqlExtend.GetSysTime();

            int iMaoZhong = 0;
            int iPiZhong = 0;
            int iRongQiZhong = 0;
            if (!string.IsNullOrEmpty(txtPiZhong.Text)&&!string.IsNullOrEmpty(txtMaoZhong.Text))
            {
                int.TryParse(txtMaoZhong.Text, out iMaoZhong);
                int.TryParse(txtPiZhong.Text, out iPiZhong);

                if (!string.IsNullOrEmpty(txtRongQiZhong.Text))
                {
                    int.TryParse(txtRongQiZhong.Text, out iRongQiZhong);
                }

                int iJingZhong =iMaoZhong- iPiZhong - iRongQiZhong;
                txtJingZhong.Text = iJingZhong.ToString();
            }
        }

        private DiBangInfo DiBangCheck()
        {
            DiBangInfo dibanginfo = new DiBangInfo();

            string pinming = txtPinMing.Text.Trim();
            string chehao = txtCheHao.Text.Trim();
            string other = txtOther.Text.Trim();

            if (string.IsNullOrEmpty(pinming))
            {
                txtPinMing.Focus();
                throw new Exception("品名不能为空!");
            }
            if (string.IsNullOrEmpty(chehao))
            {
                txtCheHao.Focus();
                throw new Exception("车号不能为空!");
            }

            StringBuilder strb = new StringBuilder();
            strb.Append(@"SELECT CHENG_DATE,PIN_MING,CHE_HAO,WEIGHT,MaoZhong,PiZhong,RongQiNum,RongQiZhong,
JingZhong,OTHER,IMAGE_ID,CompleteFlag,CREATE_USER_ID,CREATE_TIME,LAST_EVENT_NAME,LAST_EVENT_USER_ID,
LAST_EVENT_TIMEKEY
FROM DB_DIBANG WHERE (COMPLETEFLAG!='Y' OR COMPLETEFLAG IS NULL)");

            SqlCommand cmd = new SqlCommand();
            if (!string.IsNullOrEmpty(pinming))
            {
                strb.Append(" AND PIN_MING={0}PIN_MING");
                cmd.Parameters.Add(new SqlParameter("PIN_MING", pinming));
            }
            if (!string.IsNullOrEmpty(chehao))
            {
                strb.Append(" AND CHE_HAO={0}CHE_HAO");
                cmd.Parameters.Add(new SqlParameter("CHE_HAO", chehao));
            }
            if (!string.IsNullOrEmpty(other))
            {
                strb.Append(" AND OTHER={0}OTHER");
                cmd.Parameters.Add(new SqlParameter("OTHER", other));
            }
            strb.Append(" ORDER BY LAST_EVENT_TIMEKEY DESC");
            cmd.CommandText = string.Format(strb.ToString(), ConstParam.DbChar);

            DataTable dt = sqlLib.GetDataSet(cmd).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                if (dt.Rows.Count > 1)
                {
                    FrmDiBangSel frmSel = new FrmDiBangSel();
                    frmSel._DataTable = dt;
                    if (frmSel.ShowDialog() == DialogResult.OK)
                    {
                        dibanginfo = frmSel._DiBangInfo;
                    }
                }
                else
                {
                    dibanginfo.ChengZhongDate=dt.Rows[0]["CHENG_DATE"].ToString();
                    dibanginfo.PinMing=dt.Rows[0]["PIN_MING"].ToString();
                    dibanginfo.CheHao=dt.Rows[0]["CHE_HAO"].ToString();
                    dibanginfo.ChengZhong=dt.Rows[0]["WEIGHT"].ToString();

                    dibanginfo.MaoZhong=Base64Encoding.UnBaseEnconding(dt.Rows[0]["MaoZhong"].ToString());
                    dibanginfo.PiZhong=Base64Encoding.UnBaseEnconding(dt.Rows[0]["PiZhong"].ToString());
                    dibanginfo.RongQiNum=dt.Rows[0]["RongQiNum"].ToString();
                    dibanginfo.RongQiZhong=Base64Encoding.UnBaseEnconding(dt.Rows[0]["RongQiZhong"].ToString());
                    dibanginfo.JingZhong=Base64Encoding.UnBaseEnconding(dt.Rows[0]["JingZhong"].ToString());
                    dibanginfo.ChengZhongOther=dt.Rows[0]["OTHER"].ToString();
                    dibanginfo.LastEventTimeKey = dt.Rows[0]["LAST_EVENT_TIMEKEY"].ToString();
                }
            }

            if (string.IsNullOrEmpty(dibanginfo.CheHao))
            {
                WeightMode = InputMode.MaoZhong;
                ckbNewAdd.Checked = true;
                lblVLastEventTimeKey.Text = string.Empty;
            }
            else
            {
                WeightMode = InputMode.PiZhong;
                ckbNewAdd.Checked = false;
                lblVLastEventTimeKey.Text = dibanginfo.LastEventTimeKey;
            }

            return dibanginfo;
        }

        private void FrmDiBangInput_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.serialport.Dispose();
            this.serialport.Close();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            DiBangInfo dibanginfo = DiBangCheck();
            if (!string.IsNullOrEmpty(dibanginfo.CheHao))
            {
                txtPinMing.Text = dibanginfo.PinMing;
                txtCheHao.Text = dibanginfo.CheHao;
                txtOther.Text = dibanginfo.ChengZhongOther;

                txtMaoZhong.Text = dibanginfo.MaoZhong;
                txtPinMing.Text = dibanginfo.PiZhong;
                txtRongQiNum.Text = dibanginfo.RongQiNum;
                txtRongQiZhong.Text = dibanginfo.RongQiZhong;
            }
        }

        private void txtWeight_TextChanged(object sender, EventArgs e)
        {
            if (WeightMode.Equals(InputMode.MaoZhong))
            {
                txtMaoZhong.Text = txtWeight.Text;
            }
            else if (WeightMode.Equals(InputMode.PiZhong))
            {
                txtPiZhong.Text = txtWeight.Text;
            }
        }

        private void txtPinMing_KeyDown(object sender, KeyEventArgs e)
        {
            //3个txtbox使用了这个方法
            if (e.KeyCode.Equals(Keys.Enter))
            {
                DiBangInfo dibanginfo = DiBangCheck();
                if (!string.IsNullOrEmpty(dibanginfo.CheHao))
                {
                    txtPinMing.Text = dibanginfo.PinMing;
                    txtCheHao.Text = dibanginfo.CheHao;
                    txtOther.Text = dibanginfo.ChengZhongOther;

                    txtMaoZhong.Text = dibanginfo.MaoZhong;
                    txtPiZhong.Text = dibanginfo.PiZhong;
                    txtRongQiNum.Text = dibanginfo.RongQiNum;
                    txtRongQiZhong.Text = dibanginfo.RongQiZhong;
                }
            }
        }

    }
}
